package pl.edu.pw.tm.zestawfiltrow.panels;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class ImagePanel extends JPanel {
	private static final long serialVersionUID = -7938716960331414266L;
	private BufferedImage scaledImage;
	private BufferedImage image;
	private BufferedImage filteredImage;
	private BufferedImage scaledFilteredImage;

	public ImagePanel() {
	}

	public BufferedImage getFilteredImage() {
		return filteredImage;
	}
	

	public BufferedImage getClearImage() {
		return image;
	}

	public void setClearImage(BufferedImage image) {
		this.image = image;
		this.scaledImage = scaleImage(image, getWidth(), getHeight() / 2, Color.WHITE);
		this.filteredImage = null;
		this.scaledFilteredImage = null;
		repaint();
		revalidate();
	}

	public void setFilteredImage(BufferedImage filteredImage) {
		this.filteredImage = filteredImage;
		this.scaledFilteredImage = scaleImage(filteredImage, getWidth(), getHeight() / 2, Color.WHITE);
		revalidate();
		repaint();
		revalidate();
	}

	public void paint(Graphics g) {
		g.clearRect(0, 0, getWidth(), getHeight());
		
		if (scaledImage != null)
			g.drawImage(scaledImage, 0, 0, null);
		if (scaledFilteredImage != null)
			g.drawImage(scaledFilteredImage, 0, scaledImage.getHeight() + 1, null);

	}

	public BufferedImage scaleImage(BufferedImage img, int width, int height, Color background) {
		int imgWidth = img.getWidth();
		int imgHeight = img.getHeight();
		if (imgWidth * height < imgHeight * width) {
			width = imgWidth * height / imgHeight;
		} else {
			height = imgHeight * width / imgWidth;
		}
		BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = newImage.createGraphics();
		try {
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
			g.setBackground(background);
			g.clearRect(0, 0, width, height);
			g.drawImage(img, 0, 0, width, height, null);
		} finally {
			g.dispose();
		}
		return newImage;
	}


}
